import { ref, unref } from 'vue'
import { useEventListener, useThrottleFn } from '@vueuse/core'

const SCREEN = {
  MD: 768,
  LG: 992,
  XL: 1200
}

const collapsed = ref(false)
const isMobile = ref(false)

export const useLayout = () => {
  const toggleCollapsed = () => {
    collapsed.value = !unref(collapsed)
    // triggerWindowResize()
  }

  return {
    collapsed,
    isMobile,
    toggleCollapsed
  }
}

export const initLayout = () => {
  const setLayout = () => {
    const currentWidth = document.body.offsetWidth
    if (currentWidth - 1 < SCREEN.MD) {
      isMobile.value = true
    } else if (currentWidth - 1 < SCREEN.LG) {
      isMobile.value = false
      collapsed.value = true
    } else {
      isMobile.value = false
      collapsed.value = false
    }
  }

  // 添加窗口变化 监听
  useEventListener(
    window,
    'resize',
    useThrottleFn(() => {
      setLayout()
    }, 300)
  )

  // 初始化
  setLayout()
}
